import 'package:flutter/material.dart';
import 'base/wqs_text.dart';
import 'base/wqs_button.dart';

import 'package:ball_lion/resources/colours.dart';

class ChoiceBar extends StatefulWidget {
  const ChoiceBar(
      {super.key,
      required this.items,
      this.initialIndex = 0,
      this.onTap,
      this.needScroll = false,
      this.radius,
      this.itemPadding,
      this.spacer,
      this.width = 56,
      this.backgroundColor = Colours.B6,
      this.unselectColor = Colours.white,
      this.textColor = Colours.white,
      this.unselectTextColor = Colours.N9,
      this.mainAxisAlignment = MainAxisAlignment.spaceBetween});

  final List<String> items;
  final int initialIndex;
  final bool needScroll;
  final double? radius;
  final double width;
  final EdgeInsets? itemPadding;
  final double? spacer;
  final MainAxisAlignment mainAxisAlignment;
  final Color backgroundColor;
  final Color unselectColor;
  final Color textColor;
  final Color unselectTextColor;
  final ValueChanged<int>? onTap;

  @override
  State<ChoiceBar> createState() => _ChoiceBarState();
}

class _ChoiceBarState extends State<ChoiceBar> {
  late var position = widget.initialIndex;

  @override
  Widget build(BuildContext context) {
    var bar = Row(
        mainAxisAlignment: widget.mainAxisAlignment,
        children: List.generate(widget.items.length,
            (index) => widget.needScroll ? flex(index) : fix(index)));

    return widget.needScroll
        ? SingleChildScrollView(scrollDirection: Axis.horizontal, child: bar)
        : bar;
  }

  Widget fix(int index) {
    return QsButton(
      width: widget.width,
      height: 24,
      onPressed: () async {
        setState(() {
          position = index;
          widget.onTap?.call(index);
        });
      },
      text: widget.items[index],
      backgroundColor:
          position == index ? widget.backgroundColor : widget.unselectColor,
      textStyle: TextStyle(
          fontSize: 14,
          fontWeight: FontWeight.w400,
          color:
              position == index ? widget.textColor : widget.unselectTextColor),
    );
  }

  Widget flex(int index) {
    return GestureDetector(
      onTap: () => setState(() {
        position = index;
        widget.onTap?.call(index);
      }),
      child: Container(
          margin: EdgeInsets.only(right: widget.spacer ?? 0),
          padding: widget.itemPadding ??
              const EdgeInsets.symmetric(horizontal: 14, vertical: 2),
          decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(widget.radius ?? 15),
              color: position == index ? Colours.main : Colours.white),
          child: QsText(widget.items[index],
              fontWeight: FontWeight.w400,
              color: position == index ? Colours.white : Colours.grey99)),
    );
  }
}
